﻿using gt.webapi.core.Entity.Common;
using gt.webapi.core.Extensions;
using gt.webapi.core.Repositories;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace gt.webapi.core.Handlers
{
    public class IpLimitHandler : DelegatingHandler
    {
        private IIpLimitRepository m_repository = null;
        public IpLimitHandler(IIpLimitRepository repository)
        {
            this.m_repository = repository ?? throw new ArgumentNullException("repository");
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string clientIp = request.GetClientRealIp();

            if (!this.m_repository.CheckIp(clientIp))
            {
                return await Task.FromResult<HttpResponseMessage>(new HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.Forbidden,
                    Content = new StringContent(Constants.ERROR_FORBIDDEN, System.Text.Encoding.UTF8, "text/plain")
                });
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }
}
